<template>
  <div class="cart">
    <receiving-address ref="address"></receiving-address>
    <el-table
      ref="multipleTable"
      :data="dataArray"
      stripe:true
      tooltip-effect="dark"
      style="width: 100%; margin-top: 20px"
      :reserve-selection="true"
      :row-key="(row) => row.shoppingId"
      @selection-change="handleSelectionChange"
      :row-class-name="rowClassName"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="商品">
        <template #default="scope">
          <div class="goods">
            <img :src="getImageSrc(scope.row.order.picture)" alt="" />
            <div class="info">
              <h4 class="title">{{ scope.row.order.title }}</h4>
              <p class="content">{{ scope.row.order.content }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="120">
        <template #default="scope">
          <p class="price">￥{{ scope.row.order.price }}</p>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="180">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.count"
            @change="handleChange($event, scope.row)"
            :min="1"
            :max="1000000000"
            style="width: 120px"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip width="100">
        <template #default="scope">
          <el-button
            type="info"
            class="delete-bar"
            @click="deleteClick(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px" class="cancle">
      <el-button @click="toggleSelection()">取消选择</el-button>
    </div>
    <div class="submit">
      <div class="total-price">
        <span>总价:￥{{ totalprice }}</span>
      </div>
      <el-button type="danger" @click="payment" class="place-order"
        >提交订单</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { alipayRoad } from "../api/alipay";
import { cartDeleteOrder, cartShow, updateGoodsCount } from "../api/cart";
import ReceivingAddress from "../components/ReceivingAddress.vue";
import { selectDefaultByOwnName } from "../api/address";
import { getImageSrc } from "@/utils/imgUtil";

// 使用 reactive 创建响应式数据
const dataArray = ref([]);
const totalprice = ref(0);
const addressData = ref({});
const multipleSelection = ref([]);

// 获取表单的引用
const multipleTable = ref(null);

// 监听 multipleSelection 和 dataArray 的变化
watch(
  multipleSelection,
  () => {
    calculateTotalPrice();
  },
  { deep: true }
);



// 获取当前的行数
const rowClassName = ({ row, rowIndex }) => {
  //把每一行的索引放进row
  row.index = rowIndex;
};

// 计算总价
const calculateTotalPrice = () => {
  let sum = 0;
  multipleSelection.value.forEach((item) => {
    sum += Number(item.order.price) * item.count;
  });
  totalprice.value = sum;
};

// 提交表单的方法
const payment = () => {
  // console.log("this.multipleSelection", multipleSelection.value);
  if (multipleSelection.value.length > 0) {
    let arr = [];
    multipleSelection.value.forEach(async (item) => {
      let params ={
        shoppingId: item.shoppingId,
        orderId: item.order.orderId,
        title: item.order.title,
        count: item.count,
        price: item.order.price,
        picture: item.order.picture,
        content: item.order.content,
        ownName: item.order.ownName,
      };
      arr.push(params);
    });
    alipayRoad({
      addId: addressData.value.id,
      tMoney: totalprice.value,
      shoppingModelList: arr,
    })
      .then((res) => {
        ElMessage.success(res.message);
        // 提交订单成功后，重新获取订单列表
        getOrderList();
      })
      .catch((err) => {
        console.log(err);
      });
  } else {
    ElMessage.error("请选择商品");
  }
};

// 删除操作
const deleteClick = (row) => {
  ElMessageBox.confirm("确认将该商品移出购物车吗, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      cartDeleteOrder({
        id: row.shoppingId,
      })
        .then((res) => {
          // 从 dataArray 中删除该行
          dataArray.value.splice(row.index, 1);
          // 重新计算总价
          calculateTotalPrice();
          ElMessage.success("删除成功");
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error("删除失败");
        });
    })
    .catch(() => {
      // 用户点击取消按钮
      ElMessage.info("已取消删除");
    });
};

// 取消选择
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTable.value.toggleRowSelection(row);
    });
  } else {
    multipleTable.value.clearSelection();
  }
};

// 处理选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  localStorage.setItem(
    "multipleSelection",
    JSON.stringify(multipleSelection.value)
  );
  calculateTotalPrice();
};

// 更新商品数量
const handleChange = (val, row) => {
  updateGoodsCount({
    count: val,
    id: row.shoppingId,
  })
    .then((res) => {
      // 更新总价
      calculateTotalPrice();
    })
    .catch((err) => {
      console.log(err);
    });
};

// 获取订单列表
const getOrderList = () => {
  cartShow({})
    .then((res) => {
      if (res.code == 0) {
        dataArray.value = res.data;
        totalprice.value = 0;
        calculateTotalPrice();
      } else if (res.code == 401) {
        ElMessage.error("您未登录，请先登录");
        useRouter().push("/login");
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

// 生命周期钩子
onMounted(() => {
  getOrderList();
  selectDefaultByOwnName({})
    .then((res) => {
      addressData.value = res.data;
    })
    .catch((err) => {
      console.log(err);
    });
});
</script>

<style lang="less" scoped>
.cart {
  width: 1260px;
  margin: 10px auto;
  background: #fff;
  padding: 10px 20px;
  .goods {
    width: 500px;
    img {
      float: left;
      width: 150px;
      height: 100px;
      margin-right: 10px;
      border-radius: 6px;
    }
    .info {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
      .title {
        margin: 0;
      }
      .content {
        height: 65px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }
  }
  .price,
  .subtotal {
    color: red;
  }
  .count {
    .itxt {
      width: 40px;
      height: 30px;
      margin: 0 10px;
    }
    button {
      display: inline-block;
      width: 20px;
      height: 20px;
      padding: 0;
      text-align: center;
      line-height: 20px;
      border: 1px solid darkgray;
      font-size: 20px;
    }
  }
  .cancle {
    float: left;
  }
  .submit {
    margin-top: 20px;
    float: right;
    width: 300px;
    height: 40px;
    .total-price {
      font-size: 20px;
      float: left;
      color: red;
      line-height: 40px;
    }
    .place-order {
      float: right;
    }
  }
}
.delete-bar {
  width: 60px;
  height: 30px;
  padding: 0;
  span {
    margin: 0;
  }
}
</style>